<template>
  <div class="flex h-full">
    <a-card class="mr-2 py-2 h-full" :body-style="{ height: '100%', padding: '0 8px', display: 'flex', flexDirection: 'column' }">
      <SearchComb class="w-56" placeholder="姓名/助记码/卡号/手机号/证件号码" @search="getList" />
      <div class="mt-2">
        <a-radio-group v-model:value="executeStatus" button-style="solid" class="flex radio-style" @change="getList(formState)">
          <a-radio-button :value="0">未执行({{ countData.unexecuted || 0 }})</a-radio-button>
          <a-radio-button :value="1">已执行({{ countData.executed || 0 }})</a-radio-button>
        </a-radio-group>
      </div>
      <BaseList :data-source="listData" :loading="loading">
        <template #renderItem="{ item }">
          <div class="py-2 px-3" :class="currentPatient.keyCode === item.keyCode ? 'active' : ''" @click="onSelect(item)">
            <div class="flex justify-between">
              <div class="flex items-center">
                <div class="text-base font-bold text-primary truncate w-16" :title="item.brName">
                  {{ item.brName }}
                </div>
                <span class="mx-1">{{ item.brXb }}</span>
                <span>{{ item.brAge }}</span>
              </div>
              <div>{{ item.ksmc }}</div>
            </div>
            <div class="flex justify-between pt-2">
              <div class="text-right text-grey">{{ formatDate(item.sj, 'YY-MM-DD HH:mm') }}</div>
              <span v-if="item.bedCode">{{ item.bedCode || '-' }}床</span>
              <LabelValue class="text-right" :class="item.lx ? 'text-orange-300' : 'text-primary'" :width="46" :value="item.lx ? '住院' : '门诊'" />
            </div>
          </div>
        </template>
      </BaseList>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="currentPatient" :show-insurance="true">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="ml-2" label="病案号" :value="currentPatient[isBGMSG ? 'brBlkh' : 'oprSn']" :width="160" />
            <LabelValue class="ml-2" label="科室" :width="140" :value="currentPatient?.ksmc" />
            <LabelValue class="ml-2" label="类别" :width="200" :value="currentPatient.ghlb" />
            <LabelValue class="ml-2" label="诊断" :width="200" :value="currentPatient.zdmc" />
            <LabelValue class="ml-2" label="过敏史" :width="140" :value="currentPatient.brGms" />
          </div>
          <div class="flex items-center">
            <LabelValue class="ml-2" label="病历号" :value="currentPatient[isBGMSG ? 'oprSn' : 'brBlkh']" :width="160" />
            <LabelValue class="ml-2" label="医生" :width="140" :value="currentPatient.empName" />
            <LabelValue class="ml-2" label="时间" :width="200" :value="currentPatient.ghsj" />
            <LabelValue class="ml-2" label="出生日期" :width="200" :value="currentPatient.brBtd" />
          </div>
        </div>
      </PatientInfoHeader>
      <a-card class="mt-2 w-full flex-1">
        <div class="mb-3">
          <a-button type="primary" :disabled="tableData.findIndex((item) => item.zxzt === 0) === -1" @click="onBatchExecute"> 执行全部 </a-button>
        </div>
        <BaseTable :loading="loading" column-code="000998" fill :extra-height="60" :data-source="tableData" :pagination="false" :scroll="{ x: 1800 }">
          <template #bodyCell="{ index, column, record }">
            <template v-if="column.dataIndex === 'xh'">
              {{ index + 1 }}
            </template>
            <template v-if="column.dataIndex === 'zxzt'">
              <a-tag v-if="record.zxzt === 0" color="blue">未执行</a-tag>
              <a-tag v-if="record.zxzt === 1" color="success">已执行</a-tag>
            </template>
            <template v-if="column.dataIndex === 'zxbz'">
              <EditCell title="执行医嘱备注">
                <SelectTags
                  v-model:value="record.zxbz"
                  show-setting
                  show-new
                  multiple
                  allow-clear
                  type="医嘱字典"
                  :search-params="{ blcybh: '执行医嘱备注' }"
                  placeholder="请输入备注"
                  @close="onChange(record)"
                />
              </EditCell>
            </template>

            <template v-if="column.dataIndex === 'action'">
              <a-button v-if="record.zxzt === 0" type="link" size="small" @click="onExecute(record)"> 执行 </a-button>
              <template v-else>
                <ConfirmModal description="撤销执行?" @confirm="onUnExecute(record)">
                  <a-button danger type="text" size="small"> 撤销 </a-button>
                </ConfirmModal>
                <a-button type="link" size="small" @click="onClickExecut(record)"> 调整执行 </a-button>
              </template>
            </template>
          </template>
          <template #footer>
            <div class="text-right mr-4 font-semibold text-base">总金额: {{ formatAmount(totalAmount) }}</div>
          </template>
        </BaseTable>
      </a-card>
      <AdjustModal v-model:open="adjustOpen" :row-data="rowData" @success="getTableData" />
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import SearchComb from '@/components/SearchComb'
import { formatDate } from '@/utils/format'
import { formatAmount } from '@/utils/format.js'
import ConfirmModal from '@/components/ConfirmModal'
import { post, get } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import BaseList from '@/components/BaseList'
import AdjustModal from '../components/AdjustModal'

const adjustOpen = ref(false)
const loading = ref(false)
const rowData = ref({})
const tableData = ref([])
const listData = ref([])
const formState = ref({})
const executeStatus = ref(0)
const countData = ref({
  unexecuted: 0,
  executed: 0
})

const currentPatient = ref({})
const totalAmount = ref(0)
const onSelect = (item) => {
  currentPatient.value = item
  // currentPatient.value.keyCode = item.keyCode
}
const onExecute = (row) => {
  if (row.lx === 0) {
    onExecuteMz([row.id])
  } else {
    onExecuteZy([row.id])
  }
}
const onUnExecute = (row) => {
  if (row.lx === 0) {
    onUnExecuteMz(row.id)
  } else {
    onUnExecuteZy(row.id)
  }
}
const onBatchExecute = () => {
  if (currentPatient.value.lx === 0) {
    onExecuteMz(tableData.value.filter((item) => item.zxzt === 0).map((item) => item.id))
  } else {
    onExecuteZy(tableData.value.filter((item) => item.zxzt === 0).map((item) => item.id))
  }
}
// 调整执行
const onClickExecut = (row) => {
  rowData.value = { ...row, lx: currentPatient.value.lx }
  adjustOpen.value = true
}
//执行门诊
const onExecuteMz = async (ids) => {
  const res = await post('/outp/mzhs/doExecuteClinicalOrder', ids)
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg || '操作成功')
  getList()
}
//撤销执行
const onUnExecuteMz = async (id) => {
  const res = await get('/outp/mzhs/doCancelExecuteClinicalOrder?yzid=' + id)
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg || '操作成功')
  getList()
}
//执行住院
const onExecuteZy = async (ids) => {
  const res = await post('/inp/clinicalOrder/execInpAdvice', {
    ids
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success('操作成功')
  getList()
}
//撤销执行住院
const onUnExecuteZy = async (id) => {
  const res = await post('inp/clinicalOrder/cancelExecInpAdvice', { id })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success('操作成功')
  getList()
}
//保存执行备注
const onChange = async (row) => {
  setTimeout(async () => {
    const { code, msg } = await post('/common/patient/saveAdviceInfo', row)
    if (code !== 0) return message.error(msg || '保存失败')
    getTableData()
  }, 100)
}
//右侧表格
const getTableData = async () => {
  tableData.value = []
  loading.value = true
  const { code, data, msg } = await post('/common/patient/getAdviceInfoByKeyCode', {
    keyCode: currentPatient.value.keyCode,
    lx: currentPatient.value.lx,
    startDate: formState.value.startDate,
    endDate: formState.value.endDate
  })
  loading.value = false
  if (code !== 0) return message.error(msg || '请求失败')
  tableData.value = data
  if (tableData.value && tableData.value.length > 0) {
    totalAmount.value = tableData.value.reduce((sum, current) => {
      return Number(sum || 0) + Number(current.je || 0)
    }, 0)
  }
}

//左侧数据
const getList = async (params = false) => {
  // getListQuantity()
  if (params) {
    formState.value = params
  }
  loading.value = true
  listData.value = []
  tableData.value = []
  const { code, data, msg } = await post('/common/patient/getAdviceInfo', {
    pyjm: formState.value.searchKey,
    endDate: formState.value.endDate,
    startDate: formState.value.startDate,
    zxzt: executeStatus.value
  })
  loading.value = false
  if (code !== 0) return message.error(msg || '请求失败')
  listData.value = data
  if (executeStatus.value) {
    countData.value.executed = data.length
  } else {
    countData.value.unexecuted = data.length
  }
  getCount(executeStatus.value === 1 ? 0 : 1)
  if (data.length === 0) {
    currentPatient.value = {}
    return
  }
  // 如果当前患者不存在，则取第一个
  if (!currentPatient.value.keyCode) {
    currentPatient.value = data[0]
  } else if (data.findIndex((item) => item.keyCode === currentPatient.value.keyCode) === -1) {
    currentPatient.value = data[0]
  }
  getTableData()
}
const getCount = async (type) => {
  const { code, data } = await post('/common/patient/getAdviceInfo', {
    pyjm: formState.value.searchKey,
    endDate: formState.value.endDate,
    startDate: formState.value.startDate,
    zxzt: type
  })
  if (code !== 0) return
  if (type) {
    countData.value.executed = data.length
  } else {
    countData.value.unexecuted = data.length
  }
}
watch(
  () => currentPatient.value.keyCode,
  (val) => {
    if (val) {
      getTableData()
    } else {
      tableData.value = []
    }
  }
)
</script>

<style lang="less" scoped>
.radio-style {
  :deep(.ant-radio-button-wrapper) {
    width: 66.4%;
    padding: 0;
    text-align: center;
  }
}
</style>
